package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import com.itheima.dto.AddAddressBookDto;
import com.itheima.dto.ModifyAddressBookDto;
import com.itheima.dto.SetDefaultDto;
import com.itheima.mapper.AddressBookMapper;
import com.itheima.pojo.AddressBook;
import com.itheima.service.AddressBookService;
import com.itheima.thread.TokenThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author YangJiaHao
 */
@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public Boolean setDefault(SetDefaultDto setDefaultDto) {
        Integer result = addressBookMapper.updateIsDefaultByUserId(TokenThreadUtils.getThreadLocal().getId());
        if (result<=0){
            throw new RuntimeException("操作失败");
        }
        Integer res = addressBookMapper.updateIsDefaultById(setDefaultDto);
        return res==1;
    }

    @Override
    public AddressBook getDefault() {

        AddressBook addressBook = addressBookMapper.selectDefault(TokenThreadUtils.getThreadLocal().getId());
        if (addressBook==null){
            throw new RuntimeException("默认地址不存在");
        }
        return addressBook;
    }

    @Override
    public Boolean add(AddAddressBookDto dto) {
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(dto, addressBook);
        addressBook.setId(IdUtil.getSnowflakeNextIdStr());
        addressBook.setUserId(TokenThreadUtils.getThreadLocal().getId());
        addressBook.setIsDefault(0);
        addressBook.setIsDeleted(0);
        Integer res = addressBookMapper.insertAddressBook(addressBook);
        return res==1;
    }

    @Override
    public AddressBook getById(String id) {
        return addressBookMapper.selectById(id);
    }

    @Override
    public List<AddressBook> getList() {
        return addressBookMapper.selectByUserId(TokenThreadUtils.getThreadLocal().getId());
    }

    @Override
    public Boolean remove(String ids) {
        String[] split = ids.split(",");
        Integer res = addressBookMapper.delete(split);
        if (res!=split.length){
            throw new RuntimeException("删除失败");
        }
        return true;
    }

    @Override
    public Boolean modify(ModifyAddressBookDto dto) {
        if (dto.getIsDefault()==1){
            addressBookMapper.updateIsDefaultByUserId(TokenThreadUtils.getThreadLocal().getId());
        }
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(dto, addressBook);
        addressBook.setUserId(TokenThreadUtils.getThreadLocal().getId());
        Integer res = addressBookMapper.updateAddressBook(addressBook);
        if (res!=1){
            return false;
        }
        return true;
    }
}
